﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>

    public partial class YCAAUTOEK : DocumentBase
    {
        #region====================Properties=======================
        Queue<DataSet> JobQueue;
        DataSet SetMap = null;
        bool success = true;
        bool IsRunning = false;
        string failreason = "";
        string root = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\");
        public OracleConnection OracleDB;
        public SqlConnection SqlServerDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        INTEXDBC INTEXDBC;
        bool isrun = true;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData");
            }
        }
        public DataSet SetExt;
        string Today
        {
            get
            {
                return System.DateTime.Now.Year.ToString()
                    + m_Data.Right("00" + System.DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + System.DateTime.Now.Day.ToString(), 2);
            }
        }
        YCAAUTOEK2INTEX m_wintex;
        public SETINTEXDB Set4ITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        }
        public SETINTEXDB SetVITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetVITX");
            }
        }
        YCAAUTOEKData m_Data;
        string UserID = "";
        #region=====vwVAFARBEN_EXT=======
        CollectionViewSource vwVAFARBEN_EXT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwVAFARBEN_EXT");
            }
        }
        DataRow dwVAFARBEN_EXT
        {
            get
            {
                if (vwVAFARBEN_EXT.View == null)
                    return null;
                if ((DataRowView)vwVAFARBEN_EXT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwVAFARBEN_EXT.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwABPOS_MAT=======
        CollectionViewSource vwABPOS_MAT
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS_MAT");
            }
        }
        DataRow dwABPOS_EXT
        {
            get
            {
                if (vwABPOS_MAT.View == null)
                    return null;
                if ((DataRowView)vwABPOS_MAT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS_MAT.View.CurrentItem).Row;
            }
        }
        #endregion
        public YCAAUTOEK()
        {
            InitializeComponent();
            this.Name = "自动采购";
            JobQueue = new Queue<DataSet>();
        }
        #endregion
        BackgroundWorker bgWorker;
       
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                bgWorker = new BackgroundWorker();
                bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
                bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }

        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            IsRunning = false;
        }
        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        { 
            if (!IsRunning)
            {
                IsRunning = true;
            }            
            AutoRun();
        }
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    this.dicParamater = dicParamater;
                    OracleDB = (OracleConnection)dicParamater["OracleDB"];
                    proxy = (IntexReptServBLClient)dicParamater["proxy"];
                    m_Data = new YCAAUTOEKData(OracleDB, proxy);
                    INTEXDBC = new INTEXDBC(OracleDB, proxy);
                    #region============TESTINGDATA================ 
                    txtUserID.Text = (string)dicParamater["User"];
                    txtPassword.Password = (string)dicParamater["Pwd"];
                    #endregion
                    SetMap = new DataSet();
                   DataSet setResult=m_Data.ResetSetInterface();
                    SetMap.Merge(setResult);
                    SetExt = new DataSet();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            string Mandant = txtMANDANT.Text.ToUpper();
            string userID = m_Data.Left(txtUserID.Text.ToUpper() + "        ", 8);
            System.Security.SecureString SPassword = txtPassword.SecurePassword;
            txtLogIn.Background = new SolidColorBrush(Colors.Yellow);
            DataSet setResult = m_Data.LogIn(Mandant, userID, SPassword);
            if (setResult.Tables.Count > 0)
            {
                DataRow dwUser = setResult.Tables[0].Rows[0];
                txtSPRACHKZ.Text = dwUser["HRSPRKZ"].ToString();
                UserID = userID;
                m_Data.UserID = userID;
                this.UserID = userID;

                m_Data.WorkingDate = DateTime.Now.Year.ToString() + m_Data.Right("00" + DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + DateTime.Now.Day.ToString(), 2);
                m_Data.MANDANT = Mandant;
                m_Data.SPRACHKZ = txtSPRACHKZ.Text.Trim();
                this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "已登录";
                txtLogIn.Background = new SolidColorBrush(Colors.Green);

            }
        }  
        private void btnSaveWork_Click(object sender, RoutedEventArgs e)
        {
            SaveJob();
        }
        public void SaveJob()
        {
            DataSet SetJob = new DataSet();
            LoadJob();
            SetJob.Merge(SetExt);
            JobQueue.Enqueue(SetJob);
            if (IsRunning)
            {
                return;
            }
            if (!IsRunning)
            {
                bgWorker.RunWorkerAsync();
            }
        }
        private void dlgVAFARBEN_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView; 
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void dlgABPOS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }  
 
        public void Convert2Intex(ref bool success, ref string failreason, ref DataSet jobdata)
        {
            DataSet setResult = new DataSet();
            try
            {
                m_Data.SetExt = jobdata;
                m_Data.SetExt.Merge(SetMap);
                //m_Data.SetExt.Merge(SetData);
                setResult = m_Data.ConvertToIntex(ref success, ref failreason);
                if (!success)
                {
                    return;
                }
                jobdata.Clear();
                jobdata.Merge(setResult);
                if (m_wintex == null)
                {
                    m_wintex = new WPFExcelReport.YCAAUTOEK2INTEX(OracleDB, proxy);
                }
                //m_wintex.ReSet(Set4ITX, null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public bool Upload2Intex(ref DataSet jobdata)
        {
            bool result = true;
            try
            {
                if (m_wintex == null)
                {
                    m_wintex = new YCAAUTOEK2INTEX(OracleDB, proxy);
                }
                m_wintex.ReSet(jobdata, null);
                result = m_wintex.Execute(null);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return result;
        } 
 
        public void LoadJob()
        {
            try
            {
                SetExt = new DataSet();
                bool last = true;
                DataSet setResult = m_Data.GetJob(ref last);
                SetExt.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void AutoRun()
        {
           
            try
            {
                DataSet SetJob = new DataSet();
                if (isrun == false)
                    return;
                while (JobQueue.Count > 0)
                {
                    SetJob = JobQueue.Dequeue(); 
                    AutoConvert(SetJob);                                                    
                }               
            }
            catch (Exception ex)
            {
                IsRunning = false;
                Tracer.Error(ex.StackTrace, ex);
            } 
        }
        /// <summary>
        /// Load external data. usually this is used to load detail informations with a code.
        /// </summary>
        /// <param name="fInterID"></param>
        /// <param name="fClothNO"></param>
        /// <param name="fColorNo"></param>

        public DataSet ReadFile(string filePath)
        {
            DataSet setResult = new DataSet();
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    setResult.ReadXml(filePath);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setResult;
        }

        public void AutoConvert(DataSet jobdata)
        {
            //<VKKAUFKRS> VKKAUFLFD> VKKNEUBEN>
            try
            {
                DataSet setResult = new DataSet();
                bool result = true;
               
                success = true;
                failreason = "";
                EventDispatcher.Instance.RaiseStatus("开始转换:", StatusEventType.RunningProgress);
                this.Dispatcher.Invoke(new Action(() =>
                {
                    listABPOS.Text = "";
                    if (jobdata.Tables.Contains("EKPOS_EXT"))
                    {
                        if (jobdata.Tables["EKPOS_EXT"].Rows.Count > 0)
                        {
                            listABPOS.Text += "共转换:" + jobdata.Tables["EKPOS_EXT"].Rows.Count + "采购单;" + Environment.NewLine;
                        }
                    }
                }));   
                Convert2Intex(ref success, ref failreason, ref jobdata);
                SetVITX.Merge(jobdata);
                this.Dispatcher.Invoke(new Action(() =>
                {
                    if (SetVITX.Tables.Contains("EKKOPF"))
                    {
                        if (SetVITX.Tables["EKKOPF"].Rows.Count > 0)
                        {
                            foreach (DataRow dw in SetVITX.Tables["EKKOPF"].Rows)
                            {
                                listABPOS.Text += dw["EKKAUFKRS"].ToString() +"-"+dw["EKKAUFLFD"].ToString()+ ";" + Environment.NewLine;
                            }
                        }
                    }
                }));   
                if (!success)
                {
                    result = false;
                }
                else
                {
                    result = Upload2Intex(ref jobdata);
                    EventDispatcher.Instance.RaiseStatus("保存到Intex:", StatusEventType.StopProgress);
                } 
            }
            catch(Exception  ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
          
            }
        } 

        private void butExcelLoad_Click(object sender, RoutedEventArgs e)
        {
            m_Data.SetExt = new DataSet();
            m_Data.SetExt.Merge(SetMap);
            DataSet Result=m_Data.LoadExcelVKVV();
            if (SetData.Tables.Contains("EKPOS_EXT"))
            {
                SetData.Tables["EKPOS_EXT"].Clear();
            } 
            SetData.Merge(Result);
            SetData.AcceptChanges();  
        }
        private void butDelete_Click(object sender, EventArgs e)
        { 
            try
              {
                  if (txtDelete.Text.ToString().Trim() == "N")
                  {
                      MessageBox.Show("如果你确认删除，请将标志改为Y");
                      return;
                  }
                  if (m_wintex == null)
                  {
                      m_wintex = new YCAAUTOEK2INTEX(OracleDB, proxy);
                  }
                  listGS08N.Text = "";
                  string client = "00";
                  string krs = m_Data.Right("  " + txtEKPAUFKRS.Text.ToString().Trim(), 2);
                  string lfd = m_Data.Right("000000" + txtEKPAUFLFD.Text.ToString().Trim(), 6);
                  string pos = m_Data.Right("000" + txtEKPAUFPOS.Text.ToString().Trim(), 3);
                  m_wintex.Delete(client, krs, lfd,pos);
                  txtDelete.Text = "N";
                  listGS08N.Text =krs+lfd+ "已经成功删除！";
              }
              catch (Exception ex)
              {
                  Tracer.Error(ex.StackTrace, ex);
              }
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                /*
                DataSet Result = new DataSet();
                DataRow dwABKOPF = SetData.ABKOPF.NewRow();
                dwABKOPF["ABKMANDANT"] = "00";
                dwABKOPF["ABKAUFKRS"] = KRS;
                dwABKOPF["ABKAUFLFD"] = LFD;
                Result = m_Data.BuildData(dwABKOPF);
                SetData.Clear();
                SetData.Merge(Result, false, MissingSchemaAction.Ignore);
                if (vwABPOS != null)
                {
                    if (vwABPOS.View != null)
                    {
                        vwABPOS.View.MoveCurrentToFirst();
                    }
                }*/
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            /*
            DataSet setRpt = new DataSet();

            if (setRpt == null)
                return;
            m_DataX = new YCAAUTOEKData(dicParamater);
            m_DataX.OracleDB = this.OracleDB;
            m_DataX.proxy = this.proxy;
            if (m_DataX.exAgent._app == null)
            {
                m_DataX.exAgent = new ExcelX.ExcelLib.ExcelAgent(dicParamater);
            }
            m_rpt = new SDTAB05Report(dicParamater);
            m_rpt.dsSource = SetData;
            m_rpt.exAgent = m_DataX.exAgent;
            m_rpt.WriteExcelReport("EXCEL");
             * */
        }
    }
}